package org.simpleframework.mvc.processor.impl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;

import org.simpleframework.mvc.RequestProcessorChain;
import org.simpleframework.mvc.processor.RequestProcessor;

/**
 * jsp资源请求处理
 * @author icanci
 * @date Created in 2021/03/06 21:22
 * @version 1.0
 */
public class JspRequestProcessor implements RequestProcessor {

    /**
     * jsp请求的RequestDispatcher的名称
     */
    private static final String JSP_SERVLET         = "jsp";
    /**
     * Jsp请求资源路径前缀
     */
    private static final String JSP_RESOURCE_PREFIX = "/templates/";

    /**
     * jsp的RequestDispatcher,处理jsp资源
     */
    private RequestDispatcher   jspServlet;

    /**
     * 构造函数
     * @param servletContext RequestDispatcher
     */
    public JspRequestProcessor(ServletContext servletContext) {
        jspServlet = servletContext.getNamedDispatcher(JSP_SERVLET);
        if (null == jspServlet) {
            throw new RuntimeException("there is no jsp servlet");
        }
    }

    /**
     * jsp 处理器
     * @param requestProcessorChain 请求链
     * @return 返回是否继续执行
     * @throws Exception
     */
    @Override
    public boolean process(RequestProcessorChain requestProcessorChain) throws Exception {
        if (isJspResource(requestProcessorChain.getRequestPath())) {
            jspServlet.forward(requestProcessorChain.getRequest(), requestProcessorChain.getResponse());
            return false;
        }
        return true;
    }

    /**
     * 是否请求的是jsp资源
     * @param url 请求路径
     * @return 是否是jsp资源
     */
    private boolean isJspResource(String url) {
        return url.startsWith(JSP_RESOURCE_PREFIX);
    }
}
